import { queryFamily } from "@/api/love.api";
import { Family, LoveTime } from "@/types/Family";
import { Ref, onBeforeUnmount, onMounted, ref } from "vue";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import { timeDiff } from "@/utils/useTimeDiff";
export const useLove = (): {
  love: Ref<Family>;
  timeLen: Ref<LoveTime>;
  getFamily: () => void;
} => {
  const love = ref<Family>(new Family());
  const timeLen = ref<LoveTime>(new LoveTime());
  /**
   * 获取表白墙信息
   */
  const getFamily = async () => {
    const res = await queryFamily();
    if (res.code === 200) {
      love.value = res.data || new Family();
      if (love.value.timing) {
        setTimer();
      } else {
        timeLen.value = new LoveTime();
      }
    }
  };

  const timer = ref(0);
  const setTimer = () => {
    if (timer.value) clearInterval(timer.value);
    timer.value = setInterval(() => {
      //   timeLen.value = useTimeDiff(love.value.timing);
      const diffTime = timeDiff(love.value.timing);
      timeLen.value.year = diffTime.diffYear;
      timeLen.value.month = diffTime.diffMonth;
      timeLen.value.day = diffTime.diffDay;
      timeLen.value.hour = diffTime.diffHour;
      timeLen.value.minute = diffTime.diffMinute;
      timeLen.value.second = diffTime.diffSecond;
    }, 1000);
  };
  onMounted(() => {
    getFamily();
  });
  onBeforeUnmount(() => {
    clearInterval(timer.value);
  });
  return {
    love,
    getFamily,
    timeLen,
  };
};
